from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from ui.Ui_script_editor_dialog import Ui_Dialog_script_editor
from app.window.msg_box import Msg_box
import time
from database.db import Database


class Script_editor_signal(QObject):
    save_script = Signal(dict)
    fresh_content_with_id = Signal(int)


class Private_script_new_dialog(QDialog):
    
    def __init__(self, parent=None):
        super(Private_script_new_dialog, self).__init__(parent)
        self.ui = Ui_Dialog_script_editor()
        self.ui.setupUi(self)
        
        self.setWindowTitle('新建私有脚本')
        
        self.ui.label_group.hide()
        self.ui.comboBox_group.hide()

        self.setModal(True)  # 设置窗体为模态窗口，必须为True
        self.setWindowFlags(Qt.WindowCloseButtonHint)  # 设置窗体仅显示关闭按钮
    
        self.msg = Msg_box(self)
        
        self.signal = Script_editor_signal()

        self.device_id = -1

        self.ui.pushButton_save.clicked.connect(self.save)
    
    def slot_show_self(self,device_id:int):
        self.ui.lineEdit_name.clear()
        self.ui.textEdit_info.clear()
        self.ui.textEdit_script.clear()
        self.ui.textEdit_textfsm.clear()
        self.device_id = device_id
        self.show()


    def save(self):
        data = {
            'device_id':self.device_id,
            'name' : self.ui.lineEdit_name.text(),  
            'info' : self.ui.textEdit_info.toPlainText(),
            'content' : self.ui.textEdit_script.toPlainText(),
            'textfsm' : self.ui.textEdit_textfsm.toPlainText(),
        }
        # 数据库存储

        db = Database()
        #脚本表
        fields_list = ['name','info','content','textfsm','type',]
        values = (data['name'],data['info'],data['content'],data['textfsm'],'private')
        db.insert('scripts',fields_list,values)
        script_id = db.select('sqlite_sequence',['seq'],'name="scripts"')[0][0]
        data['id'] = script_id
        
        #设备与脚本关联
        fields_list = ['script_id','device_id']
        values = (script_id,self.device_id)
        db.insert('private_script_device',fields_list,values)
        db.close_conn()

        # 通知更新私有脚本管理器
        self.signal.save_script.emit(data)

